.extern start_kernel

.section .text.init
.globl _start, _end
_start:

  la sp, boot_stack_top
  addi sp, sp, 400
  addi sp, sp, 400
  addi sp, sp, 400
  addi sp, sp, 400
  # li t0, 0xFFFFFFDF80000000
  # sub sp, sp, t0

  call setup_vm
  call relocate

  call mm_init
  call setup_vm_final
  call task_init
  
  #set stvec = _traps
  la a0, _traps
  csrw stvec, a0

  #set sie[STIE] = 1
  li a0, 1 << 5 
  csrs sie, a0

  #set first_time_interupt
  rdtime a0
  li t0, 0x30000
  add a0,a0,t0
  call sbi_set_timer

  #set sstatus[SIE] = 1
  li a0, 1 << 1
  csrs sstatus, a0

  j start_kernel
  # j _srodata

relocate:
    # set ra = ra + PA2VA_OFFSET
    # set sp = sp + PA2VA_OFFSET (If you have set the sp before)

    ###################### 
    #   YOUR CODE HERE   #
    ######################
    li t0, 0xFFFFFFDF80000000
    add ra, ra, t0;
    add sp, sp, t0;

    # set satp with early_pgtbl

    ###################### 
    #   YOUR CODE HERE   #
    ######################
    la t1, early_pgtbl
    # sub t1, t1, t0
    srli t1, t1, 12
    li t2, 8 << 60
    or t1, t1, t2
    csrw satp, t1

    # flush tlb
    sfence.vma zero, zero

    # flush icache
    fence.i

    ret

.section .stack.init
  .space 0x1000

boot_stack_top:
.align 4
